package com.rds.common.workflowUtils;

import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.DynamicVo;
import com.rds.common.core.service.IDynamicService;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.spring.SpringUtils;
import com.rds.common.utils.uuid.SnowFlakeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WorkflowUtils {
    private static final Logger log = LoggerFactory.getLogger(WorkflowUtils.class);

    /**
     * 流程模板类型Id（rda_workflow_templete）
     */
    public final static Long  workflowTempleteTypeid = 10000811L;

    /**
     * 流程模板策略Id（rda_workflow_templete）
     */
    public final static Long  workflowTempletePolicyid = 10000816L;

    /**
     * 流程模板状态Id（rda_workflow_templete）创建状态
     */
    public final static Long  workflowTempleteCreateid = 10000834L;

    /**
     * 流程模板状态Id（rda_workflow_templete）活动状态
     */
    public final static Long  workflowTempleteActiveid = 10000833L;

    /**
     * 流程模板状态Id（rda_workflow_templete）完成状态
     */
    public final static Long  workflowTempleteCompleteid = 10000832L;

    /**
     * 流程模板状态Id（rda_workflow_templete）作废状态
     */
    public final static Long  workflowTempleteObsoletedid = 10000831L;



    /**
     * 流程模板节点类型Id（rda_node_templete）
     */
    public final static Long  nodeTempleteTypeid = 10000810L;

    /**
     * 流程模板节点策略Id（rda_node_templete）
     */
    public final static Long  nodeTempletePolicyid = 10000815L;

    /**
     * 流程模板节点状态Id（rda_node_templete）创建状态
     */
    public final static Long  nodeTempleteCreateid = 10000830L;

    /**
     * 流程模板节点状态Id（rda_node_templete）活动状态
     */
    public final static Long  nodeTempleteActiveid = 10000829L;

    /**
     * 流程模板节点状态Id（rda_node_templete）完成状态
     */
    public final static Long  nodeTempleteCompleteid = 10000828L;

    /**
     * 流程模板节点状态Id（rda_node_templete）作废状态
     */
    public final static Long  nodeTempleteObsoletedid = 10000827L;



    /**
     * 流程模板应用范围类型id(rda_workflow_templete_scope)
     */
    public final static Long workflowTempleteScopeTypeid = 10001083L;

    /**
     * 流程模板应用范围策略id(rda_workflow_templete_scope)
     */
    public final static Long workflowTempleteScopePolicyid = 10001084L;

    /**
     * 流程模板应用范围状态id(rda_workflow_templete_scope) 创建
     */
    public final static Long workflowTempleteScopeCreateid = 10001085L;

    /**
     * 流程模板应用范围状态id(rda_workflow_templete_scope) 活动
     */
    public final static Long workflowTempleteScopeActiveid = 10001086L;

    /**
     * 流程模板应用范围状态id(rda_workflow_templete_scope) 非活动
     */
    public final static Long workflowTempleteScopeinActiveid = 10001087L;



    /**
     * 流程列表类型id(rda_workflow)
     */
    public final static Long workflowTypeid = 10000807L;

    /**
     * 流程列表策略id(rda_workflow)
     */
    public final static Long workflowPolicyid = 10000814L;

    /**
     * 流程列表状态id(rda_workflow)创建
     */
    public final static Long workflowCreateid = 10000826L;

    /**
     * 流程列表状态id(rda_workflow)活动
     * 2021-12-21
     */
    public final static Long workflowActiveid = 10000825L;

    /**
     * 流程列表状态id(rda_workflow)完成
     */
    public final static Long workflowCompleteid = 10000824L;

    /**
     * 流程列表状态id(rda_workflow)作废
     */
    public final static Long workflowObsoletedid = 10000823L;

    /**
     * 流程列表节点类型id(rda_wf_node)
     */
    public final static Long wfNodeTypeid = 10000808L;

    /**
     * 流程列表节点策略id(rda_wf_node)
     */
    public final static Long wfNodePolicyid = 10000812L;

    /**
     * 流程列表节点状态id(rda_wf_node)创建
     *2021-12-21
     */
    public final static Long wfNodeCreateid = 10000818L;


    /**
     * 流程列表节点状态id(rda_wf_node)活动
     * 2021-12-21
     */
    public final static Long wfNodeActiveid = 10000817L;



    /**
     * 流程列表节点状态id(rda_wf_node)完成
     * 2021-12-21
     */
    public final static Long wfNodeCompleteid = 10001108L;

    /**
     * 流程列表节点状态id(rda_wf_node)作废
     */
    public final static Long wfNodeObsoleteid = 10001109L;

    /**
     * 流程列表节点状态id(rda_wf_node)暂停
     */
    public final static Long wfNodeSuspendid = 10001277L;

    /**
     * 流程任务类型(rda_wf_task)
     * 2021-12-21
     */
    public final static Long wfTaskTypeid = 10000809L;

    /**
     * 流程任务策略(rda_wf_task)
     * 2021-12-21
     */
    public final static Long wfTaskPolicyid = 10000813L;

    /**
     * 流程任务状态(rda_wf_task)创建
     */
    public final static Long wfTaskCreateid = 10000822L;

    /**
     * 流程任务状态(rda_wf_task)活动
     * 2021-12-21
     */
    public final static Long wfTaskActiveid = 10000821L;

    /**
     * 流程任务状态(rda_wf_task)完成
     * 2021-12-21
     */
    public final static Long wfTaskCompleteid = 10000820L;

    /**
     * 流程任务状态(rda_wf_task)作废
     * 2021-12-21
     */
    public final static Long wfTaskObsoletedid = 10000819L;

    /**
     * 流程任务状态(rda_wf_task)暂停
     * 2021-12-21
     */
    public final static Long wfTaskSuspendid = 10001421L;

    /**
     * 文档管理类型(rda_document)
     */
    public final static Long documentTypeid = 10000007L;

    /**
     * 文档管理策略(rda_document)
     */
    public final static Long documentPolicyid = 10001015L;

    /**
     * 文档管理类型(rda_document)创建
     */
    public final static Long documentCreateid = 10001017L;

    /**
     * 文档管理类型(rda_document)审批
     */
    public final static Long documentApprovedid = 10001018L;

    /**
     * 文档管理类型(rda_document)发布
     */
    public final static Long documentReleaseid = 10001019L;


    /**
     * 文档管理类型(rda_document)废弃
     */
    public final static Long documentObsoletedid = 10001020L;


    /**
     * 文档管理策略(rda_document) 文档发布
     */
    public final static Long documentReleasePolicyid = 10001016L;

    /**
     * 流程人员委托类型(rda_wf_user_agent)
     */
    public final static Long agentTypeid = 10000812L;

    /**
     * 流程人员委托策略(rda_wf_user_agent)
     */
    public final static Long agentPolicyid = 10001366L;

    /**
     * 流程人员委托状态(rda_wf_user_agent)创建
     */
    public final static Long agentCreateid = 10001367L;

    /**
     * 流程人员委托状态(rda_wf_user_agent)激活
     */
    public final static Long agentActivationid = 10001368L;
    /**
     * 流程人员委托状态(rda_wf_user_agent)作废
     */
    public final static Long agentObsoletedid = 10001369L;

    /**
     * 流程节点人员委托类型(rda_wf_node_agent_rel)
     */
    public final static Long agentNodeTypeid = 10000813L;

    /**
     * 流程节点人员委托策略(rda_wf_node_agent_rel)
     */
    public final static Long agentNodePolicyid = 10001404L;

    /**
     * 流程节点人员委托状态(rda_wf_node_agent_rel)创建
     */
    public final static Long agentNodeCreateid = 10001405L;

    /**
     * 流程节点人员委托状态(rda_wf_node_agent_rel)激活
     */
    public final static Long agentNodeActivation = 10001406L;

    /**
     * 流程节点人员委托状态(rda_wf_node_agent_rel)作废
     */
    public final static Long agentNodeObsoleted = 10001407L;

    /**
     *  创建流程接口
     * @param objectTypeid   类型
     * @param objectPolicyid 策略
     * @param objectStateid  状态
     * @param objectId       对象id
     * @param objectModuleName 对象所属模块
     * @param ObjectName      对象名
     */
    public static AjaxResult createWorkflowWithObject(Long objectTypeid, Long objectPolicyid, Long objectStateid, Long objectId, String objectModuleName, String ObjectName) {
        IDynamicService dynamicService = SpringUtils.getBean(IDynamicService.class);
        DynamicVo dynamicVo = new DynamicVo();
        dynamicVo.setTableName("rda_workflow_templete_scope");
        ArrayList<String> queryWrapper = new ArrayList<>();
        queryWrapper.add("and object_typeid=" + objectTypeid);
        queryWrapper.add("and object_policyid=" + objectPolicyid);
        dynamicVo.setQueryWrapper(queryWrapper);
        List<HashMap<String, Object>> list = dynamicService.selectList(dynamicVo);//根据类型策略查询流程模板应用范围
        String url="";
        String params="";
        String tableName="";
        if("document".equals(objectModuleName)){//文档接入流程
        }else if("wbs".equals(objectModuleName)){//wbs门接入流程
            url="/pmswbs/"+objectId;
            params="{'route':'details','treeMenu':'type_WBS'}";
            tableName="rda_pmswbs";
        }else if("projectChangeWF".equals(objectModuleName) || "projectPlayCut".equals(objectModuleName)){//变更流程接入流程
            url="/projectWorkflow/query/"+objectId;
            params="{'route':'details','treeMenu':'type_project_workflow'}";
            tableName="rda_project_workflow";
        }else if("reimbursement".equals(objectModuleName)){//报销接入流程
            url="/reimbursement/user/"+objectId;
            params="{'route':'details','treeMenu':'type_reimbursement'}";
            tableName="rda_memberlist_user";
        }else if("airticketApply".equals(objectModuleName)){//机票申请接入流程
            url="/reimbursement/airticketApply/"+objectId;
            params="{'route':'details','treeMenu':'type_airticket'}";
            tableName="rda_airticket_apply";
        }
        for(HashMap<String,Object> rdaWorkflowTempleteScope2:list){
            Map<String,Object> rdaWorkflowData=new HashMap<>();
            Long id= SnowFlakeUtils.nextId();
            rdaWorkflowData.put("id", id);
            rdaWorkflowData.put("ownerid", SecurityUtils.getUserId());
            rdaWorkflowData.put("typeid", workflowTypeid);
            rdaWorkflowData.put("policyid", workflowPolicyid);
            rdaWorkflowData.put("stateid", workflowCreateid);
            rdaWorkflowData.put("flow_templeteid", Long.valueOf(rdaWorkflowTempleteScope2.get("workflowtempleteid").toString()));
            rdaWorkflowData.put("name", ObjectName+"-"+rdaWorkflowTempleteScope2.get("name"));
            rdaWorkflowData.put("description", rdaWorkflowTempleteScope2.get("description"));
            insertRdaWorkflow(rdaWorkflowData,url,params,dynamicService);

            Map<String,Object> rdaWorkflowObjectRelData=new HashMap<>();
            rdaWorkflowObjectRelData.put("workflowid",id);
            rdaWorkflowObjectRelData.put("objectid",objectId);
            rdaWorkflowObjectRelData.put("object_typeid",rdaWorkflowTempleteScope2.get("object_typeid"));
            rdaWorkflowObjectRelData.put("object_policyid",rdaWorkflowTempleteScope2.get("object_policyid"));
            rdaWorkflowObjectRelData.put("object_stateid",rdaWorkflowTempleteScope2.get("object_stateid"));
            rdaWorkflowObjectRelData.put("object_module_name",objectModuleName);
            rdaWorkflowObjectRelData.put("purpose","approve");
            dynamicService.insertData("rda_workflow_object_rel",rdaWorkflowObjectRelData);
            //自动启动流程控制开关
            if("1".equals(rdaWorkflowTempleteScope2.get("start_up").toString())){
                return publicStartUpWorkflowList(objectId,dynamicService);
            }
        }
        return AjaxResult.success();
    }

    /**
     *  克隆节点及关系
     */
    public static int insertRdaWorkflow(Map<String,Object> rdaWorkflowData,String url,String params,IDynamicService dynamicService) {
        int row=dynamicService.insertData("rda_workflow",rdaWorkflowData);
        ArrayList<String> queryWrapper = new ArrayList<>();
        DynamicVo dynamicVo = new DynamicVo();
        dynamicVo.setTableName("rda_node_templete");
        queryWrapper.add("and workflowid="+Long.valueOf(rdaWorkflowData.get("flow_templeteid").toString()));
        dynamicVo.setQueryWrapper(queryWrapper);
        dynamicVo.setOrderBy("level");
        List<HashMap<String, Object>> list =dynamicService.selectList(dynamicVo);//查询流程模板节点表

        HashMap<Long,Long> map=new HashMap<Long,Long>();
        ArrayList<HashMap> idList=new ArrayList<HashMap>();
        for(HashMap<String,Object> rdaNodeTemplete:list){
            Long oldId =(Long)rdaNodeTemplete.get("id");
            Long id = SnowFlakeUtils.nextId();
            map.put(oldId, id);
            idList.add(map);

            Map<String,Object> rdaWfNodeData=new HashMap<>();
            rdaWfNodeData.put("id",id);
            if(rdaNodeTemplete.get("node_name")!=null){
                rdaWfNodeData.put("node_name",rdaNodeTemplete.get("node_name"));
            }
            if(rdaNodeTemplete.get("description")!=null) {
                rdaWfNodeData.put("description",rdaNodeTemplete.get("description"));
            }
            if(rdaNodeTemplete.get("level")!=null) {
                rdaWfNodeData.put("level",rdaNodeTemplete.get("level"));
            }
            if(rdaWorkflowData.get("id")!=null) {
                rdaWfNodeData.put("workflowid",rdaWorkflowData.get("id"));
            }
            if(rdaNodeTemplete.get("ancestors")!=null) {
                rdaWfNodeData.put("ancestors",rdaNodeTemplete.get("ancestors"));
            }
            if(rdaNodeTemplete.get("rdorder")!=null) {
                rdaWfNodeData.put("rdorder",rdaNodeTemplete.get("rdorder"));
            }
            if(rdaNodeTemplete.get("user_id")!=null) {
                rdaWfNodeData.put("user_id",rdaNodeTemplete.get("user_id"));
            }
            if(rdaNodeTemplete.get("role_id")!=null) {
                rdaWfNodeData.put("role_id",rdaNodeTemplete.get("role_id"));
            }
            if(rdaNodeTemplete.get("user_name")!=null) {
                rdaWfNodeData.put("user_name",rdaNodeTemplete.get("user_name"));
            }
            if(rdaNodeTemplete.get("role_name")!=null) {
                rdaWfNodeData.put("role_name",rdaNodeTemplete.get("role_name"));
            }
            rdaWfNodeData.put("create_time", DateUtils.getNowDate());
            rdaWfNodeData.put("ownerid", SecurityUtils.getUserId());
            rdaWfNodeData.put("typeid", wfNodeTypeid);
            rdaWfNodeData.put("policyid", wfNodePolicyid);
            rdaWfNodeData.put("stateid", wfNodeCreateid);
            if(rdaNodeTemplete.get("node_type")!=null) {
                rdaWfNodeData.put("node_type", rdaNodeTemplete.get("node_type"));
            }
            if(rdaNodeTemplete.get("userandor")!=null) {
                rdaWfNodeData.put("userandor", rdaNodeTemplete.get("userandor"));
            }
            if(rdaNodeTemplete.get("nodeandor")!=null) {
                rdaWfNodeData.put("nodeandor", rdaNodeTemplete.get("nodeandor"));
            }
            if(rdaNodeTemplete.get("reject_tostart")!=null) {
                rdaWfNodeData.put("reject_tostart", rdaNodeTemplete.get("reject_tostart"));
            }
            if(rdaNodeTemplete.get("reject_toprevious")!=null) {
                rdaWfNodeData.put("reject_toprevious", rdaNodeTemplete.get("reject_toprevious"));
            }
            if(rdaNodeTemplete.get("reject_skip_complete")!=null) {
                rdaWfNodeData.put("reject_skip_complete", rdaNodeTemplete.get("reject_skip_complete"));
            }
            if(rdaNodeTemplete.get("appoved_script")!=null) {
                rdaWfNodeData.put("appoved_script", rdaNodeTemplete.get("appoved_script"));
            }
            if(rdaNodeTemplete.get("reject_automatic")!=null) {
                rdaWfNodeData.put("reject_automatic", rdaNodeTemplete.get("reject_automatic"));
            }
            if(rdaNodeTemplete.get("rejecttostart_script")!=null) {
                rdaWfNodeData.put("rejecttostart_script", rdaNodeTemplete.get("rejecttostart_script"));
            }
            rdaWfNodeData.put("create_time", DateUtils.getNowDate());
            if(rdaNodeTemplete.get("is_withdraw")!=null) {
                rdaWfNodeData.put("is_withdraw", rdaNodeTemplete.get("is_withdraw"));
            }
            if(rdaNodeTemplete.get("is_agent")!=null) {
                rdaWfNodeData.put("is_agent", rdaNodeTemplete.get("is_agent"));
            }
            if(rdaNodeTemplete.get("workflowid")!=null) {
                rdaWfNodeData.put("workflowtempleteid", rdaNodeTemplete.get("workflowid"));
            }
            if(rdaNodeTemplete.get("id")!=null) {
                rdaWfNodeData.put("workflowtemplete_nodeid", rdaNodeTemplete.get("id"));
            }
            if(rdaNodeTemplete.get("x")!=null) {
                rdaWfNodeData.put("x", rdaNodeTemplete.get("x"));
            }
            if(rdaNodeTemplete.get("y")!=null) {
                rdaWfNodeData.put("y", rdaNodeTemplete.get("y"));
            }
            if(rdaNodeTemplete.get("script1")!=null) {
                rdaWfNodeData.put("script1", rdaNodeTemplete.get("script1"));
            }
            if(rdaNodeTemplete.get("script2")!=null) {
                rdaWfNodeData.put("script2", rdaNodeTemplete.get("script2"));
            }
            if(rdaNodeTemplete.get("script3")!=null) {
                rdaWfNodeData.put("script3", rdaNodeTemplete.get("script3"));
            }
            if(rdaNodeTemplete.get("script4")!=null) {
                rdaWfNodeData.put("script4", rdaNodeTemplete.get("script4"));
            }
            if(rdaNodeTemplete.get("script5")!=null) {
                rdaWfNodeData.put("script5", rdaNodeTemplete.get("script5"));
            }
            if(rdaNodeTemplete.get("email")!=null) {
                rdaWfNodeData.put("email", rdaNodeTemplete.get("email"));
            }
            rdaWfNodeData.put("url", url);
            rdaWfNodeData.put("params", params);
            dynamicService.insertData("rda_wf_node",rdaWfNodeData);
        }
        queryWrapper = new ArrayList<>();
        dynamicVo = new DynamicVo();
        dynamicVo.setTableName("rda_workflow2_node_templete_rel");
        queryWrapper.add("and workflowid="+Long.valueOf(rdaWorkflowData.get("flow_templeteid").toString()));
        dynamicVo.setQueryWrapper(queryWrapper);
        List<HashMap<String, Object>> Rel_list =dynamicService.selectList(dynamicVo);
        for(HashMap<String,Object> rdaNodeRELTemplete:Rel_list){
            Long id = SnowFlakeUtils.nextId();
            Long fromid=Long.valueOf(rdaNodeRELTemplete.get("fromid").toString());
            Long toid=Long.valueOf(rdaNodeRELTemplete.get("toid").toString());
            for (int i=0;i<idList.size();i++){
                HashMap<Long,Long> relmap=idList.get(i);
                for (Long key:relmap.keySet()) {
                    if(key.equals(fromid)){
                        fromid=map.get(key);
                    }
                    if(toid.equals(key)){
                        toid=map.get(key);
                    }
                }
            }
            Map<String,Object> rdaWorkflow2NodeRelData=new HashMap<>();
            rdaWorkflow2NodeRelData.put("id",id);
            rdaWorkflow2NodeRelData.put("fromid",fromid);
            rdaWorkflow2NodeRelData.put("toid",toid);
            if(rdaWorkflowData.get("id")!=null){
                rdaWorkflow2NodeRelData.put("workflowid",rdaWorkflowData.get("id"));
            }
            if(rdaNodeRELTemplete.get("operation_type")!=null){
                rdaWorkflow2NodeRelData.put("operation_type",rdaNodeRELTemplete.get("operation_type"));
            }
            if(rdaNodeRELTemplete.get("operation_state")!=null){
                rdaWorkflow2NodeRelData.put("operation_state",rdaNodeRELTemplete.get("operation_state"));
            }
            if(rdaNodeRELTemplete.get("reject_script")!=null){
                rdaWorkflow2NodeRelData.put("reject_script",rdaNodeRELTemplete.get("reject_script"));
            }
            if(rdaNodeRELTemplete.get("road")!=null){
                rdaWorkflow2NodeRelData.put("road",rdaNodeRELTemplete.get("road"));
            }
            if(rdaNodeRELTemplete.get("road_flag")!=null){
                rdaWorkflow2NodeRelData.put("road_flag",rdaNodeRELTemplete.get("road_flag"));
            }
            if(rdaNodeRELTemplete.get("road_auto")!=null){
                rdaWorkflow2NodeRelData.put("road_auto",rdaNodeRELTemplete.get("road_auto"));
            }
            if(rdaNodeRELTemplete.get("road_attribute")!=null){
                rdaWorkflow2NodeRelData.put("road_attribute",rdaNodeRELTemplete.get("road_attribute"));
            }
            if(rdaNodeRELTemplete.get("appoved_script")!=null){
                rdaWorkflow2NodeRelData.put("appoved_script",rdaNodeRELTemplete.get("appoved_script"));
            }
            dynamicService.insertData("rda_workflow2_node_rel",rdaWorkflow2NodeRelData);
        }
        return row;
    }

    /**
     * 启动流程
     */
    public static AjaxResult publicStartUpWorkflowList(Long objectid,IDynamicService dynamicService){
        DynamicVo dynamicVo=new DynamicVo();
        dynamicVo.setTableName("rda_workflow_object_rel");
        ArrayList<String> queryWrapper = new ArrayList<>();
        queryWrapper.add("and objectid = " + objectid);
        dynamicVo.setQueryWrapper(queryWrapper);
        List<HashMap<String, Object>> rdaWorkflowObjectRelList =dynamicService.selectList(dynamicVo);
        Long[] Workflowids=new Long[1];
        for(HashMap<String,Object> rdaWorkflowObjectRel:rdaWorkflowObjectRelList){

            Map<String,Object> rdaWorkflowObjectRelData=new HashMap<>();
            rdaWorkflowObjectRelData.put("object_module_name",rdaWorkflowObjectRel.get("object_module_name"));
            rdaWorkflowObjectRelData.put("objectid",rdaWorkflowObjectRel.get("objectid"));
            rdaWorkflowObjectRelData.put("object_policyid",rdaWorkflowObjectRel.get("object_policyid"));
            rdaWorkflowObjectRelData.put("object_stateid",rdaWorkflowObjectRel.get("object_stateid"));
            String checkTips=objectCheck(rdaWorkflowObjectRelData,"文档启动流程",dynamicService);
            if(!checkTips.isEmpty()){
                return AjaxResult.error(checkTips);
            }
            Workflowids[0]=Long.valueOf(rdaWorkflowObjectRel.get("workflowid").toString());
            HashMap<String, Object> getStateid=dynamicService.selectDataById("rda_workflow",Workflowids[0]);
            if(getStateid==null){
                return AjaxResult.error("启动失败当前无相关流程数据");
            }
            Long stateid=Long.valueOf(getStateid.get("stateid").toString());
            if(!stateid.equals(workflowCreateid)){
                return AjaxResult.error("当前任务已启动，请勿重复启动");
            }

            dynamicVo=new DynamicVo();
            dynamicVo.setTableName("rda_wf_node");

            queryWrapper = new ArrayList<>();
            queryWrapper.add("and workflowid = " + rdaWorkflowObjectRel.get("workflowid"));
            queryWrapper.add("and node_type = " + 1);
            dynamicVo.setQueryWrapper(queryWrapper);
            List<HashMap<String, Object>> WfNodeList =dynamicService.selectList(dynamicVo);
            String nodeNames="";
            for(HashMap<String,Object> rdaWfNode:WfNodeList){
                if(rdaWfNode.get("user_id")==null){
                    nodeNames+=rdaWfNode.get("node_name")+",";
                }
            }
            if(!nodeNames.isEmpty()){
                return AjaxResult.error("当前任务有节点未指定用户，自动启动失败，未设置用户的节点名有："+nodeNames.substring(0,nodeNames.lastIndexOf(",")));
            }
            return startUpWorkflowList(Workflowids,dynamicService);

        }
        return AjaxResult.error("自动启动失败当前无相关流程数据");
    }

    /**
     * 校验
     *
     * @param rdaWorkflowObjectRel 节点ID
     * @param module 功能模块名
     * @return 错误提示信息
     */
    public static String objectCheck(Map<String,Object> rdaWorkflowObjectRel,String module,IDynamicService dynamicService){
        String checkTips="";
        if("document".equals(rdaWorkflowObjectRel.get("object_module_name").toString())){
            HashMap<String,Object> document=dynamicService.selectDataById("rda_document",Long.valueOf(rdaWorkflowObjectRel.get("objectid").toString()));
            if("文档启动流程".equals(module)){
                Long polisyId=Long.valueOf(document.get("policyid").toString());
                Long stateId=Long.valueOf(document.get("stateid").toString());
                Long objectPolisyId =Long.valueOf(rdaWorkflowObjectRel.get("object_policyid").toString());
                Long objectStateId=Long.valueOf(rdaWorkflowObjectRel.get("object_stateid").toString());
                if(polisyId.equals(objectPolisyId) && stateId.equals(objectStateId)){
                    checkTips="";
                }else{
                    checkTips="状态不满足流程自动启动条件";
                }
            }
        }
        return checkTips;
    }

    /**
     * 启动流程
     */
    public static AjaxResult startUpWorkflowList(Long[] ids,IDynamicService dynamicService){
        for (int i=0;i<ids.length;i++) {
            HashMap<String, Object> getStateid=dynamicService.selectDataById("rda_workflow",ids[i]);
            Long stateid =Long.valueOf(getStateid.get("stateid").toString());
            if (!stateid.equals(workflowCreateid)) {
                return AjaxResult.error("当前任务已启动，请勿重复启动");
            }
            DynamicVo dynamicVo=new DynamicVo();
            dynamicVo.setTableName("rda_wf_node");

            ArrayList<String> queryWrapper = new ArrayList<>();
            queryWrapper.add("and workflowid = " + ids[i]);
            queryWrapper.add("and node_type = " + 1);
            dynamicVo.setQueryWrapper(queryWrapper);
            List<HashMap<String, Object>> WfNodeList =dynamicService.selectList(dynamicVo);
            String nodeNames="";
            for(HashMap<String,Object> rdaWfNode:WfNodeList){
                if(rdaWfNode.get("user_id")==null){
                    nodeNames+=rdaWfNode.get("node_name")+",";
                }
            }
            if(!nodeNames.isEmpty()){
                return AjaxResult.error("当前任务有节点未指定用户，自动启动失败，未设置用户的节点名有："+nodeNames.substring(0,nodeNames.lastIndexOf(",")));
            }

            //将流程设置为活动状态
            Map<String,Object> data=new HashMap<>();
            queryWrapper = new ArrayList<>();
            queryWrapper.add("id="+ids[i]);
            data.put("stateid",workflowActiveid);
            data.put("modify_time",DateUtils.getNowDate());
            dynamicService.updateData("rda_workflow",data,queryWrapper);

            //将开始节点设置为完成状态
            data=new HashMap<>();
            queryWrapper = new ArrayList<>();
            queryWrapper.add("workflowid="+ids[i]+" and node_type="+0);
            data.put("stateid",wfNodeCompleteid);
            data.put("accomplish_time",DateUtils.getNowDate());
            data.put("cost_time_day",0);
            data.put("start_time",DateUtils.getNowDate());
            dynamicService.updateData("rda_wf_node",data,queryWrapper);


            dynamicVo=new DynamicVo();
            dynamicVo.setTableName("rda_wf_node");
            //查询开始节点
            queryWrapper = new ArrayList<>();
            queryWrapper.add("and workflowid = " + ids[i]);
            queryWrapper.add("and node_type = " + 0);
            dynamicVo.setQueryWrapper(queryWrapper);
            List<HashMap<String, Object>> startNode =dynamicService.selectList(dynamicVo);
            for(HashMap<String,Object> startNodes:startNode){

                dynamicVo=new DynamicVo();
                dynamicVo.setTableName("rda_workflow2_node_rel");
                //查询关系表开始节点下级
                queryWrapper = new ArrayList<>();
                queryWrapper.add("and fromid = " + startNodes.get("id"));
                dynamicVo.setQueryWrapper(queryWrapper);
                List<HashMap<String, Object>> startMapList =dynamicService.selectList(dynamicVo);
                for(HashMap<String,Object> startList:startMapList){
                    //更新开始节点下级更新为活动状态
                    data=new HashMap<>();
                    queryWrapper = new ArrayList<>();
                    queryWrapper.add("id="+startList.get("toid"));
                    data.put("stateid",wfNodeActiveid);
                    data.put("start_time",DateUtils.getNowDate());
                    dynamicService.updateData("rda_wf_node",data,queryWrapper);


                    HashMap<String, Object> rdaWfNodeMap=dynamicService.selectDataById("rda_wf_node",Long.valueOf(startList.get("toid").toString()));
                    String[] userId=rdaWfNodeMap.get("user_id").toString().split(",");
                    for(int k=0;k<userId.length;k++) {
                        String userIdK=userId[k];
                        Long userIdJ=Long.valueOf(userIdK);

                        data=new HashMap<>();
                        Long id = SnowFlakeUtils.nextId();
                        data.put("id",id);
                        data.put("workflowid",ids[i]);
                        data.put("nodeid",rdaWfNodeMap.get("id"));
                        //是否委托
                        data.put("task_name",rdaWfNodeMap.get("node_name")+ "的任务");
                        data.put("description",rdaWfNodeMap.get("node_name")+ "的任务");
                        data.put("user_id",userIdJ);
                        data.put("ownerid",SecurityUtils.getUserId());
                        data.put("typeid",wfTaskTypeid);
                        data.put("policyid",wfTaskPolicyid);
                        data.put("stateid",wfTaskActiveid);
                        data.put("transfer",false);
                        data.put("original_id",userIdJ);
                        data.put("create_time",DateUtils.getNowDate());
                        data.put("start_time",DateUtils.getNowDate());
                        dynamicService.insertData("rda_wf_task",data);

                        //插入流程任务关系表
                        data=new HashMap<>();
                        data.put("id",SnowFlakeUtils.nextId());
                        data.put("taskid",id);
                        data.put("nodeid",rdaWfNodeMap.get("id"));
                        dynamicService.insertData("rda_node2_task_rel",data);
                    }
                }

            }
        }
        return AjaxResult.success();
    }
}
